package com.song.config.mybatis;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;
import com.song.annotation.SensitiveData;
import com.song.annotation.SensitiveField;
import com.song.common.SecretKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * mybatis 对新增数据中需要加密的数据加密（仅新增时生效）
 */
@Slf4j
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class EncryptInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        //args对应的是注解@Signature中args的参数类型
        MappedStatement mappedStatement = (MappedStatement) args[0];
        //实体对象
        Object entity = args[1];
        if ("INSERT".equalsIgnoreCase(mappedStatement.getSqlCommandType().name())) {
            encrypt(entity);
        }else if ("UPDATE".equalsIgnoreCase(mappedStatement.getSqlCommandType().name())){
            Map<String, Object> map = (Map) entity;
            Object data = map.get("et");
            encrypt(data);
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    /**
     * 对敏感数据进行加密
     * @param data
     * @throws IllegalAccessException
     */
    public void encrypt(Object data) throws IllegalAccessException {
        if (data != null){
            Class<?> parameterObjectClass = data.getClass();
            SensitiveData sensitiveData = AnnotationUtils.findAnnotation(parameterObjectClass, SensitiveData.class);
            if (ObjectUtils.isNotEmpty(sensitiveData)){
                Field[] fields = parameterObjectClass.getDeclaredFields();
                for (Field field : fields) {
                    SensitiveField sensitiveField = field.getAnnotation(SensitiveField.class);
                    if (ObjectUtils.isNotEmpty(sensitiveField)){
                        field.setAccessible(true);
                        Object object = field.get(data);
                        if (object instanceof String){
                            String value = (String) object;
                            SM4 sm4 = SmUtil.sm4(Base64.decode(SecretKey.SM4_KEY));
                            String encrypt = sm4.encryptBase64(value);
                            field.set(data, encrypt);
                        }
                    }
                }
            }
        }
    }
}
